import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import jssc.SerialPortException;

import org.json.JSONException;
import org.json.JSONObject;

public class VeloThread implements Runnable {
	private Serveur _serv;
	private Thread _t;
	private String idVelo;
	private final int TIMEOUT = 10000000;
	private final int PORT = 18000;
	private final String ADRESSE_PORT = "127.0.0.1";
	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;

	VeloThread(Serveur serv) {
		_serv = serv;
		idVelo = "5";
		_t = new Thread(this);
		_t.start();
	}

	@Override
	public void run() {
		while (true) {
			try {
				// wait button
				String readed;
				do {
					byte buffer[];
					buffer = _serv.getSerialPort().readBytes(2);
					readed = new String(buffer);
				} while (!readed.contains("OK"));

				// CONNEXION SOCKET
				InetSocketAddress socketAdress = new InetSocketAddress(
						ADRESSE_PORT, PORT);

				socket = new Socket();
				socket.bind(null);
				socket.connect(socketAdress, TIMEOUT);
				out = new PrintWriter(socket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));

				// Envoie message au serveur
				// JSON
				JSONObject param = new JSONObject();
				try {
					param.put("entity", "1");
					param.put("idVelo", idVelo);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				out.println(param.toString());

				// Reception message serveur
				String reponseServeur = in.readLine();
				String messageSerial = "";
				if (reponseServeur.compareTo("0") == 0) {
					messageSerial = "OK";
				} else if (reponseServeur.compareTo("1") == 0) {
					messageSerial = "KO";
				} else if (reponseServeur.compareTo("2") == 0) {
					messageSerial = "PR";
				} else if (reponseServeur.compareTo("3") == 0) {
					messageSerial = "NA";
				}

				// Réponse au vélo
				_serv.getSerialPort().writeBytes(messageSerial.getBytes());

				socket.close();

			} catch (SerialPortException e) {
				e.printStackTrace();
			} catch (IOException e) {

			}
		}
	}
}
